package com.igeek.service;

import com.igeek.dao.Orderdao;
import com.igeek.domain.Order;
import com.igeek.domain.OrderItem;
import com.igeek.domain.Pagination;
import com.igeek.domain.Product;
import com.igeek.utils.JDBCTools;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.commons.dbutils.DbUtils;
import sun.misc.Request;

import javax.swing.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Orderservice {
    Orderdao dao =new Orderdao();
    public void save(Order order) {
        Connection conn =null;
        try {
            conn=JDBCTools.getConnection();
            //把连接放到ThreadLocal中
            JDBCTools.local.set(conn);
            //开启事务
            conn.setAutoCommit(false);
            dao.save(order);
            for (OrderItem item:order.getOrderItems()){
                dao.saveorder(item);
            }
            conn.commit();
        } catch (SQLException e) {
            DbUtils.rollbackAndCloseQuietly(conn);
            e.printStackTrace();
        }
        //提交事务


    }

    public void update(Order order) {
        dao.update(order);
    }

    public List<Order> findAllorder(String uid) {
        List<Order> orderList = new ArrayList<>();
        orderList=dao.findAllorder(uid);
        for (Order order:orderList)
        {
            String oid=order.getOid();
            List<OrderItem> items =dao.findAllitems(oid);
            for (OrderItem item:items){
                String itemid=item.getItemid();
                Product product=dao.findproduct(itemid);
                item.setProduct(product);
            }
            order.setOrderItems(items);
        }
        return orderList;
    }

    public Pagination<Order> getPageData(int page, int i) {
        Pagination<Order> data=new Pagination<>();
        List<Order> orders =dao.getPageData(page,i);
        data.setData(orders);
        int count=dao.getCount();
        int totalPage=(int)Math.ceil((double)count/i);
        data.setCount(count);
        data.setTotalPage(totalPage);
        //设置分页条
        data.setPage(page);
        data.setBar();
        return data;

    }
}
